//
// dir_UNIX.cpp
// libprotea
// Tools Library for the Protea Project / Directory management functionality, specific to UNIX
// Copyright (C) 2003, 2004, 2005 eXegeSys, Inc.
// Copyright (C) 2008 Bruce A. James
//
// This program is part of the Protea Project.
//
// The Protea Project is free software; you can redistribute it and/or modify it 
// under the terms of the GNU General Public License as published by the 
// Free Software Foundation, either version 3 of the License, or (at your 
// option) any later version.
//
// The Protea Project is distributed in the hope that it will be useful, but 
// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY 
// or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 
// for more details.
// 
// You should have received a copy of the GNU General Public License along 
// with this program.  If not, see <http://www.gnu.org/licenses/>.
// 
// Please send correspondence to:
// 
// theproteaproject@gmail.com
//

#include "../OS_defines.h"
#ifdef OS_UNIX

#include "../defines.h"
#include "dir.h"
#include "../AppHandler/AppInterface.h"
#include "../defns.h"

void XCDirectorySearch::Close() {
	INFUNC( XCDirectorySearch::Close, NULL )
	if (dir) {
		int temp = closedir( dir );
		if (temp < 0)
			RAISEOSERROR();
	};
	dir = NULL;
	OUTFUNC()
};

bool XCDirectorySearch::Search( const char* name, char* found ) {
	INFUNC( opendir, NULL )
	bool result;
	Close();
	dir = opendir( name );
	if (dir == NULL)
		RAISEOSERROR();

	result = NextFile( found );
	OUTFUNCRET( result );
};

bool XCDirectorySearch::NextFile( char* found ) {
	INFUNC( NextFile, NULL )
	bool retval = false;
	
	if (dir == NULL)
		return false;

	dirent* temp = readdir( dir );
	if (temp != NULL) {
		strcpy( found, temp->d_name );
		retval = true;
	};

	OUTFUNCRET( retval )
};

void XCChDir( char* directory ) {
	INFUNC( XCChDir, NULL );
	if (chdir( directory ) == -1)
		RAISEOSERROR();
	OUTFUNC();
};

bool XCDirNextFile(DIR_HANDLE_TYPE dir, char* found)
{
	bool retval = false;

	dirent* temp = readdir( dir );
	if (temp != NULL)
	{
		strcpy( found, temp->d_name );
		retval = true;
	};

	return retval;
};

DIR_HANDLE_TYPE XCDirFirstFile(const char* name, char* found)
{
	DIR_HANDLE_TYPE retval;

	retval = opendir( name );
	if (retval == NULL)
	{
		//cout << "ERROR:" << strerror(errno) << endl;
		throw 1;
	};

	XCDirNextFile( retval, found );
	return retval;
};

void XCDirClose(DIR_HANDLE_TYPE dir)
{	
	int temp = closedir( dir );
	if (temp < 0)
	{
		//cout << "ERROR:" << strerror(errno) << endl;
		throw 1;
	};
};

#endif // OS_UNIX
